using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace GameOverlayWPF
{
    public partial class LoginWindow : Window
    {
        public bool IsLoggedIn { get; private set; } = false;
        private bool _isPasswordVisible = false;

        public LoginWindow()
        {
            InitializeComponent();
            
            // 设置窗口拖动
            this.MouseLeftButtonDown += (s, e) =>
            {
                if (e.ChangedButton == MouseButton.Left)
                {
                    this.DragMove();
                }
            };

            // 聚焦到用户名输入框
            this.Loaded += (s, e) =>
            {
                UsernameTextBox.Focus();
            };

            // 处理窗口关闭事件
            this.Closing += LoginWindow_Closing;
            
            // 同步 PasswordBox 和 PasswordTextBox 的内容
            PasswordBox.PasswordChanged += (s, e) =>
            {
                if (!_isPasswordVisible && PasswordBox.Password != PasswordTextBox.Text)
                {
                    PasswordTextBox.Text = PasswordBox.Password;
                }
            };
            
            PasswordTextBox.TextChanged += (s, e) =>
            {
                if (_isPasswordVisible && PasswordTextBox.Text != PasswordBox.Password)
                {
                    PasswordBox.Password = PasswordTextBox.Text;
                }
            };
        }

        private void LoginWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
        {
            // 如果用户直接关闭窗口（未登录），设置DialogResult为false
            if (!IsLoggedIn)
            {
                this.DialogResult = false;
            }
        }

        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            await PerformLogin();
        }

        private void UsernameTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                PasswordBox.Focus();
            }
        }

        private async void PasswordBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                await PerformLogin();
            }
        }

        private async void PasswordTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                await PerformLogin();
            }
        }

        private void TogglePasswordBtn_Click(object sender, RoutedEventArgs e)
        {
            _isPasswordVisible = !_isPasswordVisible;
            
            if (_isPasswordVisible)
            {
                // 显示明文密码
                PasswordTextBox.Text = PasswordBox.Password;
                PasswordBox.Visibility = Visibility.Collapsed;
                PasswordTextBox.Visibility = Visibility.Visible;
                PasswordTextBox.Focus();
                PasswordTextBox.SelectionStart = PasswordTextBox.Text.Length;
            }
            else
            {
                // 隐藏密码
                PasswordBox.Password = PasswordTextBox.Text;
                PasswordTextBox.Visibility = Visibility.Collapsed;
                PasswordBox.Visibility = Visibility.Visible;
                PasswordBox.Focus();
            }
        }

        private async Task PerformLogin()
        {
            var username = UsernameTextBox.Text?.Trim() ?? string.Empty;
            // 根据当前显示的输入框获取密码
            var password = _isPasswordVisible ? PasswordTextBox.Text : PasswordBox.Password;
            password = password ?? string.Empty;

            // 验证输入
            if (string.IsNullOrEmpty(username))
            {
                ShowError("请输入用户名");
                UsernameTextBox.Focus();
                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                ShowError("请输入密码");
                PasswordBox.Focus();
                return;
            }

            // 禁用登录按钮和输入框
            SetLoadingState(true);

            try
            {
                var result = await AuthService.LoginAsync(username, password);

                if (result != null && result.Success && !string.IsNullOrEmpty(result.Token))
                {
                    IsLoggedIn = true;
                    System.Diagnostics.Debug.WriteLine($"登录成功: {result.User?.Username}");
                    
                    // 关闭登录窗口
                    this.DialogResult = true;
                    this.Close();
                }
                else
                {
                    // 显示具体的错误信息
                    string errorMessage = "登录失败";
                    if (result != null && !string.IsNullOrEmpty(result.Message))
                    {
                        errorMessage = result.Message;
                    }
                    else
                    {
                        errorMessage = "登录失败，请检查用户名和密码";
                    }
                    ShowError(errorMessage);
                    SetLoadingState(false);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"登录错误: {ex.Message}");
                // 显示详细的错误信息
                string errorMessage = ex.Message;
                
                // 如果是网络错误，提供更友好的提示
                if (ex.Message.Contains("网络") || ex.Message.Contains("连接") || ex.Message.Contains("超时"))
                {
                    errorMessage = "网络连接失败，请检查网络设置";
                }
                // 如果是用户名或密码错误
                else if (ex.Message.Contains("用户名") || ex.Message.Contains("密码") || ex.Message.Contains("登录失败"))
                {
                    errorMessage = ex.Message;
                }
                // 其他错误
                else
                {
                    errorMessage = $"登录失败: {ex.Message}";
                }
                
                ShowError(errorMessage);
                SetLoadingState(false);
            }
        }

        private void ShowError(string message)
        {
            ErrorTextBlock.Text = message;
            ErrorTextBlock.Visibility = Visibility.Visible;
        }

        private void SetLoadingState(bool isLoading)
        {
            LoginButton.IsEnabled = !isLoading;
            UsernameTextBox.IsEnabled = !isLoading;
            PasswordBox.IsEnabled = !isLoading;
            LoadingTextBlock.Visibility = isLoading ? Visibility.Visible : Visibility.Collapsed;
            // 注意：加载时不清除错误提示，让用户能看到之前的错误信息
            // 只有在显示新错误时才更新ErrorTextBlock
        }

        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            // 关闭窗口，DialogResult会自动设置为false
            this.Close();
        }
        
        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开系统默认浏览器访问注册页面
                Process.Start(new ProcessStartInfo
                {
                    FileName = "https://www.maqt.top/",
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"打开浏览器失败: {ex.Message}");
                MessageBox.Show($"无法打开浏览器: {ex.Message}\n\n请手动访问: https://www.maqt.top/", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
    }
}

